package com.java110.mall.user.cmd.wechat;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.WechatFactory;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.WechatConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.vo.ResultVo;

import java.util.UUID;

/**
 * 获取微信分享参数
 */
@Java110Cmd(serviceCode = "wechat.getShareWechatParam")
public class GetShareWechatParamCmd extends Cmd {
    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        Assert.hasKeyAndValue(reqJson, "url", "未包含url");

    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {


        JSONObject data = new JSONObject();

        String appId = MappingCache.getValue(WechatConstant.MALL_WECHAT_DOMAIN, "wechatAppId");
        String appSecret = MappingCache.getValue(WechatConstant.MALL_WECHAT_DOMAIN, "wechatAppSecret");


        String accessToken = WechatFactory.getAccessToken(appId, appSecret);
        String jsapiTicket = WechatFactory.getTicket(appId, accessToken);
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
        String params = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + reqJson.getString("url");
        //将字符串进行sha1加密
        String signature = WechatFactory.getSHA1(params);
        //微信appId
        data.put("appId", appId);
//        data.put("accessToken", accessToken);
//        data.put("jsapi_ticket", jsapiTicket);
        data.put("timestamp", timestamp);
        data.put("nonceStr", noncestr);
        data.put("signature", signature);

        context.setResponseEntity(ResultVo.createResponseEntity(data));

    }
}
